package wrapper

import (
	"github.com/suiyunonghen/dxsvalue"
	"strings"
)

type MergeOp byte

const (
	MO_Custom  MergeOp = iota
	MO_Replace         //碰到相同的就替换
	MO_Normal          //执行默认操作，对于object的，碰到相同的就合并并集，Array的也是取并集
)

func (this *SuperValue) ValueByPathEx(path ...string) *SuperValue {
	val := this.val.ValueByPath(path...)
	if val == nil {
		return nil
	}
	return NewSVFromVal(val)
}

func (this *SuperValue) Double() float64 {
	return this.val.Double()
}

func (this *SuperValue) SetKeyInt(key string, val int64) {
	this.val.SetKeyInt(key, val)
}

func (this *SuperValue) SetKeyString(key string, val string) {
	this.val.SetKeyString(key, val)
}

func (this *SuperValue) SetKeyBool(key string, val bool) {
	this.val.SetKeyBool(key, val)
}

func (this *SuperValue) SetKeyDouble(key string, val float64) {
	this.val.SetKeyDouble(key, val)
}

func (this *SuperValue) Find(name string) *SuperValue {
	val := this.val.ValueByName(name)
	if val == nil {
		return nil
	}
	return NewSVFromVal(val)
}

func (this *SuperValue) ValueByPath(path string) *SuperValue {
	val := this.val.ValueByPath(strings.Split(path, ".")...)
	if val == nil {
		return nil
	}
	return NewSVFromVal(val)
}

func (this *SuperValue) AsDouble(name string, def float64) float64 {
	return this.Float64ByName(name, def)
}

func (this *SuperValue) MergeWith(val *SuperValue, mergefunc func(keyPath string, oldv *SuperValue, newv *SuperValue) MergeOp) {
	this.val.MergeWith(val.val, func(keyPath string, oldv *dxsvalue.DxValue, newv *dxsvalue.DxValue) dxsvalue.MergeOp {
		op := mergefunc(keyPath, NewSVFromVal(oldv), NewSVFromVal(newv))
		return dxsvalue.MergeOp(op)
	})
}

func (this *SuperValue) Merge(val *SuperValue) {
	this.val.MergeWith(val.val, func(keyPath string, oldv *dxsvalue.DxValue, newv *dxsvalue.DxValue) dxsvalue.MergeOp {
		if newv.DataType == dxsvalue.VT_Object && (oldv == nil || oldv.DataType == dxsvalue.VT_Object) {
			//fmt.Printf("Normal:%s\n", keypath)
			return dxsvalue.MO_Normal
		}
		return dxsvalue.MO_Replace // 直接替换
	})
}
